package com.black.cat.jvm.classpath.impl;

import com.black.cat.jvm.classpath.Entry;
import com.black.cat.jvm.classpath.EntryFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author blackcat
 * @create 2021/8/11 14:54
 * @version: 1.0
 * @description:组合
 */
@Slf4j
public class CompositeEntry implements Entry {

    private final List<Entry> entryList = new ArrayList<>();


    public CompositeEntry(String pathList) {
        String[] paths = pathList.split(File.pathSeparator);
        for (String path : paths) {
            entryList.add(EntryFactory.create(path));
        }
    }


    @Override
    public byte[] readClass(String className) throws IOException {
        for (Entry entry : entryList) {
            try {
                return entry.readClass(className);
            } catch (Exception ignored) {
                //ignored
                log.info(entry.toString());
            }
        }
        throw new IOException("class not found " + className);
    }

    @Override
    public String toString() {
        String[] strs = new String[entryList.size()];
        for (int i = 0; i < entryList.size(); i++) {
            strs[i] = entryList.get(i).toString();
        }
        return String.join(File.pathSeparator, strs);
    }
}
